import { toast } from "@/utils";
import Taro from "@tarojs/taro";

function request(url, method, requestData?, options?) {
  const params = {
    // url: process.env.TARO_APP_DEV_API + url, process无法使用，先使用本地地址代替
    url: "/api" + url,
    method,
    data: requestData,
    ...options,
  };
  Taro.showLoading({ title: "加载中" });
  console.log("Request params:", params); // 添加日志
  return new Promise((resolve, reject) => {
    return Taro.request({
      ...params,
      success: function (res) {
        console.log("Response:", res); // 添加日志
        const { data, code, msg, rows, total } = res.data;
        if (code === 0) {
          toast(msg);
          resolve(data);
        } else if (code == 1) {
          resolve({ rows, total });
        } else {
          toast(msg);
          reject(new Error(msg));
        }
      },
      fail: function (err) {
        console.error("Request failed:", err); // 添加日志
        reject(err);
      },
      complete: () => Taro.hideLoading(), // 注意此处修正
    });
  });
}

export const get = (url, data?) => {
  if (data) {
    url = `${url}?${Object.entries(data)
      .map(([key, value]) => `${key}=${value}`)
      .join("&")}`;
  }
  return request(url, "GET");
};

export const post = (url, data?, flag = false, options = {}) => {
  if (flag) {
    url = `${url}?${Object.entries(data)
      .map(([key, value]) => `${key}=${value}`)
      .join("&")}`;
  }
  return request(url, "POST", data, options);
};

export const put = (url, data?, options = {}) => {
  return request(url, "PUT", data, options);
};

export const del = (url, options = {}) => {
  return request(url, "DELETE", null, options);
};
